#include "ParticleSystem.h"

ParticleSystem::ParticleSystem(Image* i)
{
	image = i;
	blendMode = NORMAL_BLEND;
}

ParticleSystem::~ParticleSystem(void)
{
	for (std::vector<Particle*>::iterator it = particleList.begin(); it!=particleList.end(); ++it)
	{
		delete (*it);
		it = particleList.erase(it);
		if(it == particleList.end())
			break;
	}
}

void ParticleSystem::spawn()
{
	for(int x=0; x<5; x++)
	{
		Particle* p = new Particle();

		p->xVel = randFloat(-4,4);
		p->yVel = randFloat(-4,4);
		p->color = Color(0,155,255,144);

		p->xPos = 0;
		p->yPos = 0;

		p->width = 40;
		p->height = 40;
		p->life = 45;

		addParticle(p);
	}
}
void ParticleSystem::updateParticle(Particle* p)
{
	if(p->life < 30)
	{
		p->width -= 1.5 * p->width/40;
		p->height -= 1.5 * p->height/40;

	}else{
		p->width += .8;
		p->height += .8;
	}
	p->color.r++;
	p->color.g-=5;
	p->color.a-=4;



}

void ParticleSystem::renderParticle(Particle* p, float xOffset, float yOffset, float interpolation)
{
	setColor(p->color);
	image->draw(p->xPos + p->xVel*interpolation + xOffset - p->xVel, p->yPos + p->yVel*interpolation + yOffset - p->yVel, p->width, p->height);
}

void ParticleSystem::update()
{
	spawn();
	for (std::vector<Particle*>::iterator it = particleList.begin(); it!=particleList.end(); ++it)
	{
		Particle* p = (*it);

		updateParticle(p);
		//commit movement
		p->xPos += p->xVel;
		p->yPos += p->yVel;

		//handle life/deletion of particle
		p->life--;
		if(p->life <=0)
		{
			delete p;
			it = particleList.erase(it);
			if(it == particleList.end())
				break;
		}
	}
}

void ParticleSystem::render(float x, float y, float interpolation)
{
	glEnable(GL_BLEND);
	if(blendMode == NORMAL_BLEND)
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	if(blendMode == ADDITIVE_BLEND)
		glBlendFunc(GL_SRC_ALPHA,GL_ONE);

	for (std::vector<Particle*>::iterator it = particleList.begin(); it!=particleList.end(); ++it)
	{
		renderParticle((*it), x, y, interpolation);
	}
	glDisable(GL_BLEND);
}

void ParticleSystem::addParticle(Particle* p)
{
	particleList.push_back(p);
}
